import React, { useEffect, useState } from "react";
import {
  NavBar,
  Icon,
  InputItem,
  WingBlank,
  WhiteSpace,
  Button,
  Toast,
} from "antd-mobile";
import { sendCode } from "../../api/login";
import { verifyCode } from '../../api/regist'

import "./index.css";
import msg from "./msg.png";
const num = 5;
let code = null;
export default function VerifyCode(props) {
  const [count, setCount] = useState(num);
  const [isabled, setIsabled] = useState(true);

  useEffect(async () => {
    sendCodeHandle();
  }, []);

  async function sendCodeHandle() {
    //  获取验证码
    const phone = localStorage.getItem("phone");
    await sendCode(phone);
    //  发送成功后，倒计时
    const timeid = setInterval(() => {
      setCount((count) => {
        if (count === 1) {
          clearInterval(timeid);
        }
        return count - 1;
      });
    }, 1000);
  }
  function resendCodeHandle() {
    if (count !== 0) return;
    setCount(num);
    sendCodeHandle();
  }
  async function registeHandle() {
    const phone = localStorage.getItem("phone");
    const result = await verifyCode(phone, code);
    // console.log(result)
    if (result.data.success) {
      props.history.push("/registerPassword");
    } else {
      Toast.fail(result.data.message);
    }
  }

  return (
    <div className="wrap">
      <NavBar
        mode="light"
        icon={<Icon type="left" color="#000" />}
        onLeftClick={() => props.history.push("/registerPhone")}
      >
        硅谷注册
      </NavBar>
      <WhiteSpace size="lg"></WhiteSpace>

      <WingBlank size="lg">
        <div className="img">
          <img src={msg} alt="" />
        </div>
        <WhiteSpace size="lg"></WhiteSpace>
        <WingBlank size="lg">
          <div>
            我们将以短信或电话的形式将验证码发送给您，请注意接听0575/025/0592/010等开头的电话
          </div>
        </WingBlank>
        <WhiteSpace size="lg"></WhiteSpace>

        <div className="code">
          <InputItem
            placeholder="请输入手机验证码"
            onChange={(value) => {
              code = value.trim();
              setIsabled(!/^\d{1,}$/.test(code));
              // console.log(isabled);
            }}
          ></InputItem>
          <button
            className={count ? "code-btn" : "code-btn active"}
            onClick={resendCodeHandle}
          >
            {!count ? "重新发送" : "剩余" + count + "s"}
          </button>
        </div>
        <WingBlank size="lg">
          <Button
            className="code-next"
            type="warning"
            disabled={isabled}
            onClick={registeHandle}
          >
            下一步
          </Button>
        </WingBlank>
        <WingBlank size="lg">
          遇到问题了?
          <a href="">请联系客服</a>
        </WingBlank>
      </WingBlank>
    </div>
  );
}
